import Vue from 'vue'
import VueRouter from 'vue-router'
import tabbar from '@/components/tabbar.vue'
import store from '@/store'

// 按需加载
// import Home from '@/views/Home.vue'
const Home = () => import('@/views/home')
const Question = () => import('@/views/question')
const Video = () => import('@/views/video')
const Mine = () => import('@/views/mine')
const Login = () => import('@/views/login')
const Article = () => import('@/views/article')
const Profile = () => import('@/views/mine/components/profile')
const Chat = () => import('@/views/mine/components/chat')

// 执行了vueRouter里面的install方法
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    // components
    components: {
      // default
      default: Home,
      tabbar: tabbar
    }
  },
  {
    path: '/article',
    name: 'article',
    // components
    component: Article
  },
  {
    path: '/question',
    name: 'Question',
    components: {
      // default
      default: Question,
      tabbar: tabbar
    }
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    // 异步组件？ 按需加载
    // component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/video',
    name: 'Video',
    components: {
      // default
      default: Video,
      tabbar: tabbar
    }
  },
  {
    path: '/mine',
    name: 'Mine',
    components: {
      // default
      default: Mine,
      tabbar: tabbar
    }
  },
  {
    path: '/mine/profile',
    name: 'Profile',
    component: Profile
  },
  {
    path: '/mine/chat',
    name: 'Chat',
    component: Chat
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

const router = new VueRouter({
  routes
})

// 每次进入某个页面的时候 拦截到的函数
router.beforeEach((to, from, next) => {
  if (!store.state.user.token && to.path === '/mine') {
    return next('/login?returnUrl=' + to.fullPath)
  }

  store.commit('user/clearToken')// 取消请求
  // next是放行的，如果不执行next那么什么都显示。
  next()
})

export default router
